package com.yan.controller;

import java.util.List;

import javax.servlet.http.HttpSession;
import com.yan.controller.viewModel.looker.BookInfo;
import com.yan.controller.viewModel.looker.BookRatingInfo;
import com.yan.controller.viewModel.sort.SortInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import com.yan.service.AdminService;
import com.yan.service.BooksService;
import com.yan.service.SortService;
import com.yan.service.SysAdminService;
import com.yan.vo.Page;

@Controller
@RequestMapping("/looker")
public class LookerController {
	//@Autowired自动装配，无需自己实例化
	@Autowired
	private BooksService bookService;

	@Autowired
	private AdminService adminService;

	@Autowired
	private SysAdminService sysAdminService;

	@Autowired
	private SortService sortService;

	//跳转到登录界面
	@RequestMapping("/index")
	public String toIndex() {
		return "login";
	}

	//网站初始页面控制器
	@RequestMapping("/showOther")
	public String toShowOther(Model model, BookInfo book) {

		if (book.getSid() != null) {
			//往前台传数据，可以传对象，可以传List，
			// jsp通过el表达式 ${}可以获取到，类似于request.setAttribute("sts",sts)效果一样
			//将book.sid传给show.jsp中
			model.addAttribute("sid", book.getSid());
		}
		if (book.getBname()!=null&&"".equals(book.getBname())) {
			model.addAttribute("bname", book.getBname());//将图书的名称传到jsp中
		}

		//执行查询操作，将查询到的数据传到jsp
			Page page = bookService.getAllBooks(book);
			List<BookRatingInfo> list = bookService.selectBookTuijian();
			model.addAttribute("page", page);
			model.addAttribute("currentPage", book.getCurrentPage());
			model.addAttribute("totalPage", page.getTotalPage());
			model.addAttribute("list",list);

		return "show";
	}
	
	//游客图书查询页面
	@RequestMapping("/borrow")
	public String toBorrow(Model model, Integer id) {
		//通过id查询图书
		BookInfo book = bookService.getBook(id);
		//将查询到的book对象传到jsp
		model.addAttribute("book", book);
		List<BookRatingInfo> list=bookService.selectBookRating(id);
		model.addAttribute("list",list);
		return "borrows";
	}


	/*
	 * 被@ModelAttribute注释的方法会在此controller类的每个方法执行前被执行
	 */
	@ModelAttribute("sorts")
	public List<SortInfo> findAllSorts(HttpSession session) throws InstantiationException, IllegalAccessException {
		List<SortInfo> sorts = sortService.findAll();
		//将sorts存放于session中，所有jsp页面都可访问
		session.setAttribute("sorts", sorts);
		return sorts;
	}
	
}
